package com.mzmarket.market.console.controller;

import com.mzmarket.market.console.domain.MessageVO;
import com.mzmarket.market.console.domain.ProductCellVO;
import com.mzmarket.market.console.domain.ProductDetailVO;
import com.mzmarket.market.console.domain.ProductListVO;
import com.mzmarket.market.module.entity.Category;
import com.mzmarket.market.module.entity.Product;
import com.mzmarket.market.module.service.CategoryService;
import com.mzmarket.market.module.service.ProductService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Slf4j
@RestController
public class ProductController {

    @Autowired
    private ProductService productService;

    @Autowired
    private CategoryService categoryService;

    @RequestMapping("/admin/product/insert")
    public MessageVO productInsert(@RequestParam(required = false, name = "title") String title,
                                   @RequestParam(required = false, name = "images") String images,
                                   @RequestParam(required = false, name = "description") String description,
                                   @RequestParam(required = false, name = "saleNum") Integer saleNum,
                                   @RequestParam(required = false, name = "favoriteNum") Integer favoriteNum,
                                   @RequestParam(required = false, name = "categoryId") Long categoryId,
                                   @RequestParam(required = false, name = "price") Double price
    ) {
        Long result = null;

        try {
            result = productService.edit(null, title, images, description, saleNum, price, categoryId, favoriteNum);
        } catch (RuntimeException e) {
            log.warn(e.getMessage());
        }
        return result != null ? new MessageVO().setMessage("id = " + result) : new MessageVO().setMessage("Insert " +
                "failed");
    }

    @RequestMapping("/admin/product/update")
    public MessageVO productUpdate(@RequestParam(required = false, name = "id") Long id,
                                   @RequestParam(required = false, name = "title") String title,
                                   @RequestParam(required = false, name = "images") String images,
                                   @RequestParam(required = false, name = "description") String description,
                                   @RequestParam(required = false, name = "saleNum") Integer saleNum,
                                   @RequestParam(required = false, name = "favoriteNum") Integer favoriteNum,
                                   @RequestParam(required = false, name = "categoryId") Long categoryId,
                                   @RequestParam(required = false, name = "price") Double price) {
        Long result = null;

        try {
            result = productService.edit(id, title, images, description, saleNum, price, categoryId, favoriteNum);
        } catch (RuntimeException e) {
            log.warn(e.getMessage());
        }
        return result != null ? new MessageVO().setMessage("id = " + result) : new MessageVO().setMessage("Updated " +
                "failed");
    }

    @RequestMapping("/admin/product/delete")
    public MessageVO productDelete(@RequestParam(name = "id", required = false) Long id) {
        int result = 0;

        try {
            result = productService.delete(id);
        } catch (Exception e) {
            log.warn(e.getMessage());
        }

        return result == 1 ? new MessageVO().setMessage("Deleted Successfully") : new MessageVO().setMessage("Delete " +
                "failed");
    }

    @RequestMapping("/admin/product/list")
    public ProductListVO productList(@RequestParam(name = "page", required = false) Long page,
                                     @RequestParam(name = "keyword", required = false) String keyword) {
        Integer pageSize = 3; //定义每页显示的数据量
        List<ProductCellVO> listVO = new ArrayList<>();
        List<Product> productList = null;

        try {
            productList = productService.getPageList(pageSize, page, keyword, "console");
        } catch (Exception e) {
            log.warn(e.getMessage());
        }
        if (productList != null) {
            for (Product product : productList) {//遍历productList,提取Product的字段按照CellVO的格式存入AdminListVO
                Category category = null;
                try {
                    category = categoryService.getById(product.getCategoryId());
                } catch (Exception e) {
                    log.warn("Category get failed");
                    return new ProductListVO();
                }
                if (category == null) {
                    log.warn("Category not found");//存在脏数据不加入列表
                } else {
                    listVO.add(new ProductCellVO()
                            .setId(product.getId())
                            .setPrice(product.getPrice())
                            .setTitle(product.getTitle())
                            .setImage(product.getImages().split("&")[0])
                            .setFavoriteNum(product.getSaleNum())
                            .setCategoryName(category.getName())
                    );
                }
            }

            return new ProductListVO()
                    .setTotal(productService.count(keyword))
                    .setList(listVO)
                    .setPageSize(pageSize);
        } else {
            return new ProductListVO();
        }
    }

    @RequestMapping("/admin/product/detail")
    public ProductDetailVO productDetail(@RequestParam(name = "id", required = false) Long id) {
        Product product = null;

        try {
            product = productService.getById(id);
        } catch (Exception e) {
            log.warn(e.getMessage());
        }

        if (product != null) {
            String createTime = LocalDateTime.ofInstant(
                    Instant.ofEpochSecond(product.getCreateTime()),
                    ZoneId.systemDefault()
            ).format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));

            String updateTime = LocalDateTime.ofInstant(
                    Instant.ofEpochSecond(product.getUpdateTime()),
                    ZoneId.systemDefault()
            ).format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));

            Category category = null;
            try {
                category = categoryService.getById(product.getCategoryId());
            } catch (Exception e) {
                log.warn("Category get failed");
                return new ProductDetailVO();
            }
            if (category != null) {
                return new ProductDetailVO()
                        .setDescription(product.getDescription())
                        .setImages(Arrays.asList(product.getImages().split("&")))
                        .setSaleNum(product.getSaleNum())
                        .setTitle(product.getTitle())
                        .setPrice(product.getPrice())
                        .setCategoryImage(category.getImage())
                        .setCategoryName(category.getName())
                        .setCreateTime(createTime)
                        .setUpdateTime(updateTime);
            } else {
                log.warn("Category not found");
                return new ProductDetailVO();//脏数据不展示
            }
        } else {
            return new ProductDetailVO();
        }
    }

}
